package server

import (
	"fmt"
	"jian-picture-service/biz"
	"log"
	"net/http"
	"strconv"
)

// 测试服务是否正常
func monitorHandle(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("content-type", r.Header.Get("content-type"))
	_, _ = w.Write([]byte("ok"))
}

func userAddHandle(w http.ResponseWriter, r *http.Request) {
	req := &biz.UserAddReq{}
	code := doPrepare(r, req)
	if code != biz.SuccessCode {
		w.WriteHeader(code)
		return
	}
	err := req.UserAdd()
	if err != nil {
		checkError(err, w, r)
		return
	}
}

func userListHandle(w http.ResponseWriter, r *http.Request) {
	req := &biz.UserListReq{}
	code := doPrepare(r, req)
	if code != biz.SuccessCode {
		w.WriteHeader(code)
		return
	}
	info, err := req.UserList()
	if err != nil {
		checkError(err, w, r)
		return
	}
	doEnd(r, w, info)
}

func userLoginHandle(w http.ResponseWriter, r *http.Request) {
	req := &biz.UserLoginReq{}
	code := doPrepare(r, req)
	if code != biz.SuccessCode {
		w.WriteHeader(code)
		return
	}
	info, err := req.UserLogin()
	if err != nil {
		checkError(err, w, r)
		return
	}
	doEnd(r, w, info)
}

func userUpdateHandle(w http.ResponseWriter, r *http.Request) {
	req := &biz.UserUpdateReq{}
	code := doPrepare(r, req)
	if code != biz.SuccessCode {
		w.WriteHeader(code)
		return
	}
	err := req.UserUpdate()
	if err != nil {
		checkError(err, w, r)
		return
	}
}

func userDelHandle(w http.ResponseWriter, r *http.Request) {
	req := &biz.UserDelReq{}
	code := doPrepare(r, req)
	if code != biz.SuccessCode {
		w.WriteHeader(code)
		return
	}
	err := req.UserDel()
	if err != nil {
		checkError(err, w, r)
		return
	}
}
func userLoginInfoHandle(w http.ResponseWriter, r *http.Request) {
	req := &biz.UserLoginReq{}
	code := doPrepare(r, req)
	if code != biz.SuccessCode {
		w.WriteHeader(code)
		return
	}
	res, err := req.LoginInfo(r.Header.Get("user_id"))
	if err != nil {
		checkError(err, w, r)
		return
	}
	doEnd(r, w, res)
}

// Start 开始http server
func Start(port int) {
	var mux *http.ServeMux
	mux = http.DefaultServeMux

	mux.HandleFunc("/monitor", monitorHandle)

	mux.HandleFunc("/user/add", userAddHandle)
	mux.HandleFunc("/user/login", userLoginHandle)

	// 需要token验证的接口
	authInterface(mux, "/user/list", userListHandle)
	authInterface(mux, "/user/update", userUpdateHandle)
	authInterface(mux, "/user/del", userDelHandle)
	authInterface(mux, "/user/info/login", userLoginInfoHandle)

	err := http.ListenAndServe(":"+strconv.Itoa(port), corsMiddleware(calcTaskTime(mux)))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("http server listening on port %d...\n", port)
}
